package org.springframework.amqp.tutorials.tut2;

import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.util.StopWatch;

@RabbitListener(queues = "hello")
public class Tut2Receiver {

	private final int instance;

	public Tut2Receiver(int i) {
		this.instance = i;
	}

	@RabbitHandler
	public void receive(String in) throws InterruptedException {

		StopWatch watch = new StopWatch();
		watch.start();
		System.out.println("instance " + this.instance + " [x] Received '" + in + "'");
		doWork(in);
		watch.stop();
		System.out.println("instance " + this.instance + " [x] Done in " + watch.getTotalTimeSeconds() + "s");
	}

	private void doWork(String in) throws InterruptedException {

		for (char ch : in.toCharArray()) {
			if (ch == '.') {
				Thread.sleep(1000);
			}
		}

		// instance1只能处理单数
		int inNumber = Integer.parseInt(in.substring(in.lastIndexOf(".")+1, in.length()));
		System.out.println(inNumber);
		if (this.instance == 1 && inNumber % 2 == 0) {// 单数
			System.out.println("instance " + this.instance + "不能处理:"+in+",但是不重发");
			throw new AmqpRejectAndDontRequeueException("不重发消息");
		}
		// instance2只能处理双数
		if (this.instance == 2 && inNumber % 2 != 0) {// 单数
			System.out.println("instance " + this.instance + "不能处理:"+in+"重发");
			throw new RuntimeException();
		}
	}

}
